package utils

import (
	"fmt"

	"github.com/GoAdminGroup/go-admin/modules/logger"

	_ "github.com/aliyun/alibaba-cloud-sdk-go/sdk"
	_ "github.com/aliyun/alibaba-cloud-sdk-go/sdk/requests"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	jsoniter "github.com/json-iterator/go"
)

type Sms struct {
	AccessKeyId     string `json:"access_key_id"`
	AccessKeySecret string `json:"access_key_secret"`
	// 可选，使用 HTTPS 协议
	Scheme string `json:"scheme"`
	// 接收短信的手机号码
	PhoneNumbers string `json:"phone_numbers"`
	// 短信签名名称
	SignName string
	// 短信模板代码
	TemplateCode string
	// 短信模板参数
	TemplateParam *TemplateParam
}

type TemplateParam struct {
	Phone    string `json:"phone"`
	Sowing   int    `json:"sowing"`
	Seedling int    `json:"seedling"`
	Payment  int    `json:"payment"`
}

func GetOSSUrl(object string) (string, error) {
	client, err := oss.New("oss-cn-shanghai.aliyuncs.com", "LTAI5tP3ydzR3LJ4fBtdbHwD", "wJd87DL6aV2cZThgfwCyN97ov2jq5u")
	if err != nil {
		logger.Errorf("Failed to create client: %v", err)
		return "", fmt.Errorf("failed to create client: %v", err)
	}

	bucket, err := client.Bucket("miao-butler")
	if err != nil {
		logger.Errorf("bucket Error:%+v", err)
		return "", fmt.Errorf("bucket Error:%+v", err)
	}

	// 设置签名URL过期时间，例如1小时。
	signedURL, err := bucket.SignURL(object, "GET", 3600*24*16)
	if err != nil {
		logger.Errorf("SignURL Error:%+v", err)
		return "", fmt.Errorf("SignURL Error:%+v", err)
	}

	return signedURL, nil
}

func (s *Sms) SendSMS() string {
	// 创建客户端
	client, err := dysmsapi.NewClientWithAccessKey("cn-hangzhou", s.AccessKeyId, s.AccessKeySecret)
	if err != nil {
		return fmt.Sprintf("Failed to create client: %v", err)
	}

	// 创建请求
	request := dysmsapi.CreateSendSmsRequest()
	request.Scheme = s.Scheme             // 可选，使用 HTTPS 协议
	request.PhoneNumbers = s.PhoneNumbers // 接收短信的手机号码
	request.SignName = s.SignName         // 短信签名名称
	request.TemplateCode = s.TemplateCode // 短信模板代码
	param, err := jsoniter.Marshal(s.TemplateParam)
	if err != nil {
		return fmt.Sprintf("Failed to marshal JSON: %v", err)
	}
	request.TemplateParam = string(param) // 短信模板参数，JSON 格式

	// 发送短信
	response, err := client.SendSms(request)
	if err != nil {
		return fmt.Sprintf("Failed to send SMS: %v", err)
	}
	return response.String()
}
